package com.whfc.fvs.service.impl;

import com.whfc.common.exception.BizException;
import com.whfc.common.third.uni.UniApi;
import com.whfc.common.third.uni.UniProperties;
import com.whfc.common.third.uni.entity.ResourceSearchResponse;
import com.whfc.common.third.uni.entity.ResourceSearchResponse.ResourceItem;
import com.whfc.fvs.dao.FvsDeviceMapper;
import com.whfc.fvs.dto.FvsDeviceDTO;
import com.whfc.fvs.dto.UniResourceSyncDTO;
import com.whfc.fvs.entity.FvsDevice;
import com.whfc.fvs.enums.FvsDevicePlayMode;
import com.whfc.fvs.enums.FvsDeviceStreamMode;
import com.whfc.fvs.enums.VsPlatform;
import com.whfc.fvs.service.UniResourceSyncService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 宇视科技资源同步服务实现类
 */
@DubboService(interfaceClass = UniResourceSyncService.class, version = "1.0.0")
public class UniResourceSyncServiceImpl implements UniResourceSyncService {

    private static final Logger logger = LoggerFactory.getLogger(UniResourceSyncServiceImpl.class);

    @Autowired
    private UniApi uniApi;

    @Autowired
    private FvsDeviceMapper fvsDeviceMapper;

    @Autowired
    private UniProperties uniProperties;

    @Override
    public String getAccessToken() throws BizException {
        return uniApi.getAccessToken();
    }

    @Override
//    @Scheduled(fixedDelay = 60*1000)
    public void syncUniResourcesToFvs() {
        logger.info("开始同步宇视科技资源到视频监控分组");

        try {
            // 获取宇视科技资源列表
            List<UniResourceSyncDTO> resourceList = getUniResources();

            if (resourceList != null && !resourceList.isEmpty()) {
                // 保存资源到视频监控分组
                saveResourcesToFvs(resourceList);
                logger.info("宇视科技资源同步完成，共同步 {} 个资源", resourceList.size());
            } else {
                logger.info("未获取到宇视科技资源数据");
            }

        } catch (Exception e) {
            logger.error("同步宇视科技资源失败", e);
            throw new RuntimeException("同步宇视科技资源失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<UniResourceSyncDTO> getUniResources() {
        logger.info("开始获取宇视科技资源列表");

        List<UniResourceSyncDTO> resourceList = new ArrayList<>();

        try {
            int pageNo = 1;
            int pageSize = 100;
            boolean hasMore = true;

            while (hasMore) {
                // 调用宇视科技API获取资源列表
                ResourceSearchResponse response = uniApi.searchResources("camera", pageNo, pageSize);

                if (response != null && response.isSuccess() && response.getData() != null) {
                    List<ResourceItem> items = response.getData().getList();

                    if (items != null && !items.isEmpty()) {
                        for (ResourceItem item : items) {
                            UniResourceSyncDTO dto = convertToSyncDTO(item);
                            if (dto != null) {
                                resourceList.add(dto);
                            }
                        }

                        // 判断是否还有更多数据
                        if (items.size() < pageSize) {
                            hasMore = false;
                        } else {
                            pageNo++;
                        }
                    } else {
                        hasMore = false;
                    }
                } else {
                    logger.warn("获取宇视科技资源失败，响应: {}", response);
                    hasMore = false;
                }
            }

        } catch (BizException e) {
            logger.error("获取宇视科技资源业务异常", e);
            throw e;
        } catch (Exception e) {
            logger.error("获取宇视科技资源异常", e);
            throw new RuntimeException("获取宇视科技资源异常: " + e.getMessage(), e);
        }

        return resourceList;
    }

    @Override
    public void saveResourcesToFvs(List<UniResourceSyncDTO> resourceList) {
        logger.info("开始保存宇视科技资源到视频监控分组，资源数量: {}", resourceList.size());

        // 从配置获取部门ID，如果未配置则使用默认值1
        Integer deptId = uniProperties.getDeptId() != null ? uniProperties.getDeptId() : 1;
        logger.info("使用部门ID: {} 保存宇视科技资源", deptId);

        int successCount = 0;
        int failCount = 0;

        for (UniResourceSyncDTO dto : resourceList) {
            try {
                // 检查资源是否已存在
                FvsDevice existingDevice = fvsDeviceMapper.selectByGbId(dto.getChannelIndexCode());

                if (existingDevice == null) {
                    // 创建新的视频监控设备
                    createFvsDevice(dto, deptId);
                    successCount++;
                } else {
                    // 更新现有设备信息
                    existingDevice.setDeptId(deptId);
                    existingDevice.setName(dto.getResourceName());
                    existingDevice.setDeviceStatus(dto.getStatus());
                    existingDevice.setStreamStatus(dto.getStatus());
                    existingDevice.setUpdateTime(new Date());

                    fvsDeviceMapper.updateByPrimaryKey(existingDevice);
                    successCount++;
                }

            } catch (Exception e) {
                logger.error("保存资源失败: {}", dto.getResourceName(), e);
                failCount++;
            }
        }

        logger.info("宇视科技资源保存完成，成功: {}，失败: {}", successCount, failCount);
    }

    private void createFvsDevice(UniResourceSyncDTO dto, Integer deptId) {
        FvsDevice device = new FvsDevice();
        device.setPid(0);
        device.setDeptId(deptId);
        device.setName(dto.getResourceName());
        device.setGbId(dto.getChannelIndexCode());
        device.setSn(dto.getChannelIndexCode());
        device.setDeviceStatus(dto.getStatus());
        device.setStreamStatus(dto.getStatus());
        device.setLng(dto.getLongitude());
        device.setLat(dto.getLatitude());
        device.setCreateTime(new Date());
        device.setUpdateTime(new Date());
        device.setModel("宇视科技");
        device.setPlatform(VsPlatform.UNI.getValue().toString()); // 宇视科技平台标识
        device.setDeviceType(0);
        device.setStreamMode(FvsDeviceStreamMode.SD.getValue());
        device.setPtz(0);
        device.setDelFlag(0);
        device.setChannelNo(0);
        device.setWebcamType(2);
        device.setPlayMode(FvsDevicePlayMode.MONITOR.getValue());

        // 保存设备信息
        fvsDeviceMapper.insert(device);
    }

    /**
     * 将宇视科技资源项转换为同步DTO
     */
    private UniResourceSyncDTO convertToSyncDTO(ResourceItem item) {
        if (item == null) {
            return null;
        }

        UniResourceSyncDTO dto = new UniResourceSyncDTO();
        dto.setResourceIndexCode(item.getResourceIndexCode());
        dto.setResourceName(item.getName());
        dto.setResourceType(item.getResourceType());
        dto.setChannelIndexCode(item.getChannelIndexCode());
        dto.setChannelName(item.getChannelName());
        dto.setDeviceIndexCode(item.getDeviceIndexCode());
        dto.setDeviceName(item.getName());
        dto.setDeviceType(item.getDeviceType());
        dto.setLongitude(item.getLongitude());
        dto.setLatitude(item.getLatitude());
        dto.setInstallLocation(item.getInstallLocation());
        dto.setStatus(item.getStatus());
        dto.setSyncTime(new Date());

        return dto;
    }
}